package beautiful.butterfly.drds.data_exchange.transport.record.column;

import beautiful.butterfly.drds.data_exchange.exception.CommonErrorCode;
import beautiful.butterfly.drds.data_exchange.exception.DataExchangeException;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

public class BooleanColumn extends Column
{

    public BooleanColumn(Boolean aBoolean)
    {
        super(aBoolean, ColumnType.BOOLEAN, 1);
    }

    public BooleanColumn(final String string)
    {
        this(true);
        this.validate(string);
        if (null == string)
        {
            this.setObject(null);
            this.setByteSize(0);
        } else
        {
            this.setObject(Boolean.valueOf(string));
            this.setByteSize(1);
        }
        return;
    }

    public BooleanColumn()
    {
        super(null, ColumnType.BOOLEAN, 1);
    }

    //
    @Override
    public Boolean asBoolean()
    {
        if (null == super.getObject())
        {
            return null;
        }

        return (Boolean) super.getObject();
    }

    @Override
    public Long asLong()
    {
        if (null == this.getObject())
        {
            return null;
        }

        return this.asBoolean() ? 1L : 0L;
    }

    @Override
    public Double asDouble()
    {
        if (null == this.getObject())
        {
            return null;
        }

        return this.asBoolean() ? 1.0d : 0.0d;
    }

    @Override
    public String asString()
    {
        if (null == super.getObject())
        {
            return null;
        }

        return this.asBoolean() ? "true" : "false";
    }


    @Override
    public BigDecimal asBigDecimal()
    {
        if (null == this.getObject())
        {
            return null;
        }

        return BigDecimal.valueOf(this.asLong());
    }

    @Override
    public BigInteger asBigInteger()
    {
        if (null == this.getObject())
        {
            return null;
        }

        return BigInteger.valueOf(this.asLong());
    }

    @Override
    public Date asDate()
    {
        throw DataExchangeException.asDataExchangeException(
                CommonErrorCode.CONVERT_NOT_SUPPORT, "Bool类型不能转为Date .");
    }

    @Override
    public byte[] asBytes()
    {
        throw DataExchangeException.asDataExchangeException(
                CommonErrorCode.CONVERT_NOT_SUPPORT, "Boolean类型不能转为Bytes .");
    }

    //
    private void validate(final String string)
    {
        if (null == string)
        {
            return;
        }

        if ("true".equalsIgnoreCase(string) || "false".equalsIgnoreCase(string))
        {
            return;
        }

        throw DataExchangeException.asDataExchangeException(
                CommonErrorCode.CONVERT_NOT_SUPPORT,
                String.format("String[%s]不能转为Bool .", string));
    }
}
